package cn.topcodes.tcsf.codegen.utils;

import cn.topcodes.tcsf.codegen.domain.entity.Entity;
import cn.topcodes.tcsf.codegen.domain.entity.Field;
import cn.topcodes.tcsf.codegen.domain.entity.Program;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;

/**
 *
 * @author Unicorn
 */
public class SqliteOpenHelper {

    private static Dao programDao;
    
    private static Dao entityDao;
    
    private static Dao fieldDao;

    public static Dao getProgramDao() throws SQLException {
        if (programDao == null) {
        programDao = DaoManager.createDao(getConnectionSource(),Program.class);
        }
        return programDao;
    }
    
    public static Dao getEntityDao() throws SQLException {
        if (entityDao == null) {
            entityDao = DaoManager.createDao(getConnectionSource(),Entity.class);
        }
        return entityDao;
    }
    
    public static Dao getFieldDao() throws SQLException {
        if (fieldDao == null) {
            fieldDao = DaoManager.createDao(getConnectionSource(),Field.class);
        }
        return fieldDao;
    }

    public static void init() {
        try {
            TableUtils.createTable(getConnectionSource(), Program.class);
        }catch (Exception exception) {
            System.out.println("创建program表失败,可能已存在 : " + exception.getMessage());
        }
        try {
            TableUtils.createTable(getConnectionSource(), Entity.class);
        }catch (Exception exception) {
            System.out.println("创建entity表失败,可能已存在 : " + exception.getMessage());
        }
        try {
            TableUtils.createTable(getConnectionSource(), Field.class);
        }catch (Exception exception) {
            System.out.println("创建field表失败,可能已存在 : " + exception.getMessage());
        }
    }

    public static ConnectionSource getConnectionSource()throws SQLException {
        String connectionString ="jdbc:sqlite:data.db";
        return new JdbcConnectionSource(connectionString);
    }
    
}